package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;
    //分页查询
    @GetMapping("/list")
    public PageDTO<Item> pageInfo(Integer page,Integer size){

        PageDTO<Item> itemPageDTO = new PageDTO<>();

        Page pageInfo = new Page(page, size);
        Page pageSize = itemService.page(pageInfo);
        //设置总条数
        long total = pageSize.getTotal();
        itemPageDTO.setTotal(total);
        //分页数据
        List list = pageSize.getRecords();
        itemPageDTO.setList(list);
        return itemPageDTO;
    }
    //根据id查询商品
    @GetMapping("/{id}")
    public Item selectById(@PathVariable Long id){
        Item byId = itemService.getById(id);
        return byId;
    }
    //新增商品
    @PostMapping
    public void save(@RequestBody Item item){
        itemService.save(item);
    }
    //商品上架、下架
    @PutMapping("/status/{id}/{status}")
    public void changStatus(@PathVariable Long id,@PathVariable Integer status){
        Item byId = itemService.getById(id);
        byId.setStatus(status);
        itemService.updateById(byId);
        itemService.updateStatus(id,status);
    }
    //修改商品
    @PutMapping
    public void update(@RequestBody Item item){
        itemService.updateById(item);
    }
    //根据id删除商品
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        itemService.removeById(id);
    }
    //扣减库存
    @PutMapping("/stock/{itemId}/{num}")
    public void stock(@PathVariable Long itemId,@PathVariable Integer num){
        Item item = itemService.getById(itemId);
        Integer stock = item.getStock();
        stock = stock - num;
        item.setStock(stock);
        itemService.updateById(item);
    }
}
